[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/ -> ms-functions.php (source)

   1  <?php
   2  /**
   3   * Multisite WordPress API
   4   *
   5   * @package WordPress
   6   * @subpackage Multisite
   7   * @since 3.0.0
   8   */
   9  
  10  /**
  11   * Gets the network's site and user counts.
  12   *
  13   * @since MU (3.0.0)
  14   *
  15   * @return array Site and user count for the network.
  16   */
  17  function get_sitestats() {
  18      $stats = array(
  19          'blogs' => get_blog_count(),
  20          'users' => get_user_count(),
  21      );
  22  
  23      return $stats;
  24  }
  25  
  26  /**
  27   * Get one of a user's active blogs
  28   *
  29   * Returns the user's primary blog, if they have one and
  30   * it is active. If it's inactive, function returns another
  31   * active blog of the user. If none are found, the user
  32   * is added as a Subscriber to the Dashboard Blog and that blog
  33   * is returned.
  34   *
  35   * @since MU (3.0.0)
  36   *
  37   * @param int $user_id The unique ID of the user
  38   * @return WP_Site|void The blog object
  39   */
  40  function get_active_blog_for_user( $user_id ) {
  41      $blogs = get_blogs_of_user( $user_id );
  42      if ( empty( $blogs ) ) {
  43          return;
  44      }
  45  
  46      if ( ! is_multisite() ) {
  47          return $blogs[ get_current_blog_id() ];
  48      }
  49  
  50      $primary_blog = get_user_meta( $user_id, 'primary_blog', true );
  51      $first_blog   = current( $blogs );
  52      if ( false !== $primary_blog ) {
  53          if ( ! isset( $blogs[ $primary_blog ] ) ) {
  54              update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
  55              $primary = get_site( $first_blog->userblog_id );
  56          } else {
  57              $primary = get_site( $primary_blog );
  58          }
  59      } else {
  60          //TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog?
  61          $result = add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' );
  62  
  63          if ( ! is_wp_error( $result ) ) {
  64              update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
  65              $primary = $first_blog;
  66          }
  67      }
  68  
  69      if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) {
  70          $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
  71          $ret   = false;
  72          if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
  73              foreach ( (array) $blogs as $blog_id => $blog ) {
  74                  if ( $blog->site_id != get_current_network_id() ) {
  75                      continue;
  76                  }
  77                  $details = get_site( $blog_id );
  78                  if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
  79                      $ret = $details;
  80                      if ( get_user_meta( $user_id, 'primary_blog', true ) != $blog_id ) {
  81                          update_user_meta( $user_id, 'primary_blog', $blog_id );
  82                      }
  83                      if ( ! get_user_meta( $user_id, 'source_domain', true ) ) {
  84                          update_user_meta( $user_id, 'source_domain', $details->domain );
  85                      }
  86                      break;
  87                  }
  88              }
  89          } else {
  90              return;
  91          }
  92          return $ret;
  93      } else {
  94          return $primary;
  95      }
  96  }
  97  
  98  /**
  99   * The number of active users in your installation.
 100   *
 101   * The count is cached and updated twice daily. This is not a live count.
 102   *
 103   * @since MU (3.0.0)
 104   * @since 4.8.0 The `$network_id` parameter has been added.
 105   *
 106   * @param int|null $network_id ID of the network. Default is the current network.
 107   * @return int Number of active users on the network.
 108   */
 109  function get_user_count( $network_id = null ) {
 110      return get_network_option( $network_id, 'user_count' );
 111  }
 112  
 113  /**
 114   * The number of active sites on your installation.
 115   *
 116   * The count is cached and updated twice daily. This is not a live count.
 117   *
 118   * @since MU (3.0.0)
 119   * @since 3.7.0 The `$network_id` parameter has been deprecated.
 120   * @since 4.8.0 The `$network_id` parameter is now being used.
 121   *
 122   * @param int|null $network_id ID of the network. Default is the current network.
 123   * @return int Number of active sites on the network.
 124   */
 125  function get_blog_count( $network_id = null ) {
 126      return get_network_option( $network_id, 'blog_count' );
 127  }
 128  
 129  /**
 130   * Get a blog post from any site on the network.
 131   *
 132   * @since MU (3.0.0)
 133   *
 134   * @param int $blog_id ID of the blog.
 135   * @param int $post_id ID of the post you're looking for.
 136   * @return WP_Post|null WP_Post on success or null on failure
 137   */
 138  function get_blog_post( $blog_id, $post_id ) {
 139      switch_to_blog( $blog_id );
 140      $post = get_post( $post_id );
 141      restore_current_blog();
 142  
 143      return $post;
 144  }
 145  
 146  /**
 147   * Adds a user to a blog.
 148   *
 149   * Use the {@see 'add_user_to_blog'} action to fire an event when users are added to a blog.
 150   *
 151   * @since MU (3.0.0)
 152   *
 153   * @param int    $blog_id ID of the blog you're adding the user to.
 154   * @param int    $user_id ID of the user you're adding.
 155   * @param string $role    The role you want the user to have
 156   * @return true|WP_Error
 157   */
 158  function add_user_to_blog( $blog_id, $user_id, $role ) {
 159      switch_to_blog( $blog_id );
 160  
 161      $user = get_userdata( $user_id );
 162  
 163      if ( ! $user ) {
 164          restore_current_blog();
 165          return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) );
 166      }
 167  
 168      /**
 169       * Filters whether a user should be added to a site.
 170       *
 171       * @since 4.9.0
 172       *
 173       * @param bool|WP_Error $retval  True if the user should be added to the site, false
 174       *                               or error object otherwise.
 175       * @param int           $user_id User ID.
 176       * @param string        $role    User role.
 177       * @param int           $blog_id Site ID.
 178       */
 179      $can_add_user = apply_filters( 'can_add_user_to_blog', true, $user_id, $role, $blog_id );
 180  
 181      if ( true !== $can_add_user ) {
 182          restore_current_blog();
 183  
 184          if ( is_wp_error( $can_add_user ) ) {
 185              return $can_add_user;
 186          }
 187  
 188          return new WP_Error( 'user_cannot_be_added', __( 'User cannot be added to this site.' ) );
 189      }
 190  
 191      if ( ! get_user_meta( $user_id, 'primary_blog', true ) ) {
 192          update_user_meta( $user_id, 'primary_blog', $blog_id );
 193          $site = get_site( $blog_id );
 194          update_user_meta( $user_id, 'source_domain', $site->domain );
 195      }
 196  
 197      $user->set_role( $role );
 198  
 199      /**
 200       * Fires immediately after a user is added to a site.
 201       *
 202       * @since MU (3.0.0)
 203       *
 204       * @param int    $user_id User ID.
 205       * @param string $role    User role.
 206       * @param int    $blog_id Blog ID.
 207       */
 208      do_action( 'add_user_to_blog', $user_id, $role, $blog_id );
 209  
 210      clean_user_cache( $user_id );
 211      wp_cache_delete( $blog_id . '_user_count', 'blog-details' );
 212  
 213      restore_current_blog();
 214  
 215      return true;
 216  }
 217  
 218  /**
 219   * Remove a user from a blog.
 220   *
 221   * Use the {@see 'remove_user_from_blog'} action to fire an event when
 222   * users are removed from a blog.
 223   *
 224   * Accepts an optional `$reassign` parameter, if you want to
 225   * reassign the user's blog posts to another user upon removal.
 226   *
 227   * @since MU (3.0.0)
 228   *
 229   * @global wpdb $wpdb WordPress database abstraction object.
 230   *
 231   * @param int    $user_id  ID of the user you're removing.
 232   * @param int    $blog_id  ID of the blog you're removing the user from.
 233   * @param string $reassign Optional. A user to whom to reassign posts.
 234   * @return true|WP_Error
 235   */
 236  function remove_user_from_blog( $user_id, $blog_id = '', $reassign = '' ) {
 237      global $wpdb;
 238      switch_to_blog( $blog_id );
 239      $user_id = (int) $user_id;
 240      /**
 241       * Fires before a user is removed from a site.
 242       *
 243       * @since MU (3.0.0)
 244       *
 245       * @param int $user_id User ID.
 246       * @param int $blog_id Blog ID.
 247       */
 248      do_action( 'remove_user_from_blog', $user_id, $blog_id );
 249  
 250      // If being removed from the primary blog, set a new primary if the user is assigned
 251      // to multiple blogs.
 252      $primary_blog = get_user_meta( $user_id, 'primary_blog', true );
 253      if ( $primary_blog == $blog_id ) {
 254          $new_id     = '';
 255          $new_domain = '';
 256          $blogs      = get_blogs_of_user( $user_id );
 257          foreach ( (array) $blogs as $blog ) {
 258              if ( $blog->userblog_id == $blog_id ) {
 259                  continue;
 260              }
 261              $new_id     = $blog->userblog_id;
 262              $new_domain = $blog->domain;
 263              break;
 264          }
 265  
 266          update_user_meta( $user_id, 'primary_blog', $new_id );
 267          update_user_meta( $user_id, 'source_domain', $new_domain );
 268      }
 269  
 270      // wp_revoke_user($user_id);
 271      $user = get_userdata( $user_id );
 272      if ( ! $user ) {
 273          restore_current_blog();
 274          return new WP_Error( 'user_does_not_exist', __( 'That user does not exist.' ) );
 275      }
 276  
 277      $user->remove_all_caps();
 278  
 279      $blogs = get_blogs_of_user( $user_id );
 280      if ( count( $blogs ) == 0 ) {
 281          update_user_meta( $user_id, 'primary_blog', '' );
 282          update_user_meta( $user_id, 'source_domain', '' );
 283      }
 284  
 285      if ( $reassign != '' ) {
 286          $reassign = (int) $reassign;
 287          $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $user_id ) );
 288          $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $user_id ) );
 289  
 290          if ( ! empty( $post_ids ) ) {
 291              $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id ) );
 292              array_walk( $post_ids, 'clean_post_cache' );
 293          }
 294  
 295          if ( ! empty( $link_ids ) ) {
 296              $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id ) );
 297              array_walk( $link_ids, 'clean_bookmark_cache' );
 298          }
 299      }
 300  
 301      restore_current_blog();
 302  
 303      return true;
 304  }
 305  
 306  /**
 307   * Get the permalink for a post on another blog.
 308   *
 309   * @since MU (3.0.0) 1.0
 310   *
 311   * @param int $blog_id ID of the source blog.
 312   * @param int $post_id ID of the desired post.
 313   * @return string The post's permalink
 314   */
 315  function get_blog_permalink( $blog_id, $post_id ) {
 316      switch_to_blog( $blog_id );
 317      $link = get_permalink( $post_id );
 318      restore_current_blog();
 319  
 320      return $link;
 321  }
 322  
 323  /**
 324   * Get a blog's numeric ID from its URL.
 325   *
 326   * On a subdirectory installation like example.com/blog1/,
 327   * $domain will be the root 'example.com' and $path the
 328   * subdirectory '/blog1/'. With subdomains like blog1.example.com,
 329   * $domain is 'blog1.example.com' and $path is '/'.
 330   *
 331   * @since MU (3.0.0)
 332   *
 333   * @global wpdb $wpdb WordPress database abstraction object.
 334   *
 335   * @param string $domain
 336   * @param string $path   Optional. Not required for subdomain installations.
 337   * @return int 0 if no blog found, otherwise the ID of the matching blog
 338   */
 339  function get_blog_id_from_url( $domain, $path = '/' ) {
 340      $domain = strtolower( $domain );
 341      $path   = strtolower( $path );
 342      $id     = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
 343  
 344      if ( $id == -1 ) { // blog does not exist
 345          return 0;
 346      } elseif ( $id ) {
 347          return (int) $id;
 348      }
 349  
 350      $args   = array(
 351          'domain'                 => $domain,
 352          'path'                   => $path,
 353          'fields'                 => 'ids',
 354          'number'                 => 1,
 355          'update_site_meta_cache' => false,
 356      );
 357      $result = get_sites( $args );
 358      $id     = array_shift( $result );
 359  
 360      if ( ! $id ) {
 361          wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
 362          return 0;
 363      }
 364  
 365      wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' );
 366  
 367      return $id;
 368  }
 369  
 370  // Admin functions
 371  
 372  /**
 373   * Checks an email address against a list of banned domains.
 374   *
 375   * This function checks against the Banned Email Domains list
 376   * at wp-admin/network/settings.php. The check is only run on
 377   * self-registrations; user creation at wp-admin/network/users.php
 378   * bypasses this check.
 379   *
 380   * @since MU (3.0.0)
 381   *
 382   * @param string $user_email The email provided by the user at registration.
 383   * @return bool Returns true when the email address is banned.
 384   */
 385  function is_email_address_unsafe( $user_email ) {
 386      $banned_names = get_site_option( 'banned_email_domains' );
 387      if ( $banned_names && ! is_array( $banned_names ) ) {
 388          $banned_names = explode( "\n", $banned_names );
 389      }
 390  
 391      $is_email_address_unsafe = false;
 392  
 393      if ( $banned_names && is_array( $banned_names ) && false !== strpos( $user_email, '@', 1 ) ) {
 394          $banned_names     = array_map( 'strtolower', $banned_names );
 395          $normalized_email = strtolower( $user_email );
 396  
 397          list( $email_local_part, $email_domain ) = explode( '@', $normalized_email );
 398  
 399          foreach ( $banned_names as $banned_domain ) {
 400              if ( ! $banned_domain ) {
 401                  continue;
 402              }
 403  
 404              if ( $email_domain == $banned_domain ) {
 405                  $is_email_address_unsafe = true;
 406                  break;
 407              }
 408  
 409              $dotted_domain = ".$banned_domain";
 410              if ( $dotted_domain === substr( $normalized_email, -strlen( $dotted_domain ) ) ) {
 411                  $is_email_address_unsafe = true;
 412                  break;
 413              }
 414          }
 415      }
 416  
 417      /**
 418       * Filters whether an email address is unsafe.
 419       *
 420       * @since 3.5.0
 421       *
 422       * @param bool   $is_email_address_unsafe Whether the email address is "unsafe". Default false.
 423       * @param string $user_email              User email address.
 424       */
 425      return apply_filters( 'is_email_address_unsafe', $is_email_address_unsafe, $user_email );
 426  }
 427  
 428  /**
 429   * Sanitize and validate data required for a user sign-up.
 430   *
 431   * Verifies the validity and uniqueness of user names and user email addresses,
 432   * and checks email addresses against admin-provided domain whitelists and blacklists.
 433   *
 434   * The {@see 'wpmu_validate_user_signup'} hook provides an easy way to modify the sign-up
 435   * process. The value $result, which is passed to the hook, contains both the user-provided
 436   * info and the error messages created by the function. {@see 'wpmu_validate_user_signup'}
 437   * allows you to process the data in any way you'd like, and unset the relevant errors if
 438   * necessary.
 439   *
 440   * @since MU (3.0.0)
 441   *
 442   * @global wpdb $wpdb WordPress database abstraction object.
 443   *
 444   * @param string $user_name  The login name provided by the user.
 445   * @param string $user_email The email provided by the user.
 446   * @return array Contains username, email, and error messages.
 447   */
 448  function wpmu_validate_user_signup( $user_name, $user_email ) {
 449      global $wpdb;
 450  
 451      $errors = new WP_Error();
 452  
 453      $orig_username = $user_name;
 454      $user_name     = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
 455  
 456      if ( $user_name != $orig_username || preg_match( '/[^a-z0-9]/', $user_name ) ) {
 457          $errors->add( 'user_name', __( 'Usernames can only contain lowercase letters (a-z) and numbers.' ) );
 458          $user_name = $orig_username;
 459      }
 460  
 461      $user_email = sanitize_email( $user_email );
 462  
 463      if ( empty( $user_name ) ) {
 464          $errors->add( 'user_name', __( 'Please enter a username.' ) );
 465      }
 466  
 467      $illegal_names = get_site_option( 'illegal_names' );
 468      if ( ! is_array( $illegal_names ) ) {
 469          $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
 470          add_site_option( 'illegal_names', $illegal_names );
 471      }
 472      if ( in_array( $user_name, $illegal_names ) ) {
 473          $errors->add( 'user_name', __( 'Sorry, that username is not allowed.' ) );
 474      }
 475  
 476      /** This filter is documented in wp-includes/user.php */
 477      $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
 478  
 479      if ( in_array( strtolower( $user_name ), array_map( 'strtolower', $illegal_logins ) ) ) {
 480          $errors->add( 'user_name', __( 'Sorry, that username is not allowed.' ) );
 481      }
 482  
 483      if ( ! is_email( $user_email ) ) {
 484          $errors->add( 'user_email', __( 'Please enter a valid email address.' ) );
 485      } elseif ( is_email_address_unsafe( $user_email ) ) {
 486          $errors->add( 'user_email', __( 'You cannot use that email address to signup. We are having problems with them blocking some of our email. Please use another email provider.' ) );
 487      }
 488  
 489      if ( strlen( $user_name ) < 4 ) {
 490          $errors->add( 'user_name', __( 'Username must be at least 4 characters.' ) );
 491      }
 492  
 493      if ( strlen( $user_name ) > 60 ) {
 494          $errors->add( 'user_name', __( 'Username may not be longer than 60 characters.' ) );
 495      }
 496  
 497      // all numeric?
 498      if ( preg_match( '/^[0-9]*$/', $user_name ) ) {
 499          $errors->add( 'user_name', __( 'Sorry, usernames must have letters too!' ) );
 500      }
 501  
 502      $limited_email_domains = get_site_option( 'limited_email_domains' );
 503      if ( is_array( $limited_email_domains ) && ! empty( $limited_email_domains ) ) {
 504          $limited_email_domains = array_map( 'strtolower', $limited_email_domains );
 505          $emaildomain           = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
 506          if ( ! in_array( $emaildomain, $limited_email_domains, true ) ) {
 507              $errors->add( 'user_email', __( 'Sorry, that email address is not allowed!' ) );
 508          }
 509      }
 510  
 511      // Check if the username has been used already.
 512      if ( username_exists( $user_name ) ) {
 513          $errors->add( 'user_name', __( 'Sorry, that username already exists!' ) );
 514      }
 515  
 516      // Check if the email address has been used already.
 517      if ( email_exists( $user_email ) ) {
 518          $errors->add( 'user_email', __( 'Sorry, that email address is already used!' ) );
 519      }
 520  
 521      // Has someone already signed up for this username?
 522      $signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name ) );
 523      if ( $signup != null ) {
 524          $registered_at = mysql2date( 'U', $signup->registered );
 525          $now           = time();
 526          $diff          = $now - $registered_at;
 527          // If registered more than two days ago, cancel registration and let this signup go through.
 528          if ( $diff > 2 * DAY_IN_SECONDS ) {
 529              $wpdb->delete( $wpdb->signups, array( 'user_login' => $user_name ) );
 530          } else {
 531              $errors->add( 'user_name', __( 'That username is currently reserved but may be available in a couple of days.' ) );
 532          }
 533      }
 534  
 535      $signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email ) );
 536      if ( $signup != null ) {
 537          $diff = time() - mysql2date( 'U', $signup->registered );
 538          // If registered more than two days ago, cancel registration and let this signup go through.
 539          if ( $diff > 2 * DAY_IN_SECONDS ) {
 540              $wpdb->delete( $wpdb->signups, array( 'user_email' => $user_email ) );
 541          } else {
 542              $errors->add( 'user_email', __( 'That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.' ) );
 543          }
 544      }
 545  
 546      $result = array(
 547          'user_name'     => $user_name,
 548          'orig_username' => $orig_username,
 549          'user_email'    => $user_email,
 550          'errors'        => $errors,
 551      );
 552  
 553      /**
 554       * Filters the validated user registration details.
 555       *
 556       * This does not allow you to override the username or email of the user during
 557       * registration. The values are solely used for validation and error handling.
 558       *
 559       * @since MU (3.0.0)
 560       *
 561       * @param array $result {
 562       *     The array of user name, email and the error messages.
 563       *
 564       *     @type string   $user_name     Sanitized and unique username.
 565       *     @type string   $orig_username Original username.
 566       *     @type string   $user_email    User email address.
 567       *     @type WP_Error $errors        WP_Error object containing any errors found.
 568       * }
 569       */
 570      return apply_filters( 'wpmu_validate_user_signup', $result );
 571  }
 572  
 573  /**
 574   * Processes new site registrations.
 575   *
 576   * Checks the data provided by the user during blog signup. Verifies
 577   * the validity and uniqueness of blog paths and domains.
 578   *
 579   * This function prevents the current user from registering a new site
 580   * with a blogname equivalent to another user's login name. Passing the
 581   * $user parameter to the function, where $user is the other user, is
 582   * effectively an override of this limitation.
 583   *
 584   * Filter {@see 'wpmu_validate_blog_signup'} if you want to modify
 585   * the way that WordPress validates new site signups.
 586   *
 587   * @since MU (3.0.0)
 588   *
 589   * @global wpdb   $wpdb   WordPress database abstraction object.
 590   * @global string $domain
 591   *
 592   * @param string         $blogname   The blog name provided by the user. Must be unique.
 593   * @param string         $blog_title The blog title provided by the user.
 594   * @param WP_User|string $user       Optional. The user object to check against the new site name.
 595   * @return array Contains the new site data and error messages.
 596   */
 597  function wpmu_validate_blog_signup( $blogname, $blog_title, $user = '' ) {
 598      global $wpdb, $domain;
 599  
 600      $current_network = get_network();
 601      $base            = $current_network->path;
 602  
 603      $blog_title = strip_tags( $blog_title );
 604  
 605      $errors        = new WP_Error();
 606      $illegal_names = get_site_option( 'illegal_names' );
 607      if ( $illegal_names == false ) {
 608          $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
 609          add_site_option( 'illegal_names', $illegal_names );
 610      }
 611  
 612      /*
 613       * On sub dir installations, some names are so illegal, only a filter can
 614       * spring them from jail.
 615       */
 616      if ( ! is_subdomain_install() ) {
 617          $illegal_names = array_merge( $illegal_names, get_subdirectory_reserved_names() );
 618      }
 619  
 620      if ( empty( $blogname ) ) {
 621          $errors->add( 'blogname', __( 'Please enter a site name.' ) );
 622      }
 623  
 624      if ( preg_match( '/[^a-z0-9]+/', $blogname ) ) {
 625          $errors->add( 'blogname', __( 'Site names can only contain lowercase letters (a-z) and numbers.' ) );
 626      }
 627  
 628      if ( in_array( $blogname, $illegal_names ) ) {
 629          $errors->add( 'blogname', __( 'That name is not allowed.' ) );
 630      }
 631  
 632      /**
 633       * Filters the minimum site name length required when validating a site signup.
 634       *
 635       * @since 4.8.0
 636       *
 637       * @param int $length The minimum site name length. Default 4.
 638       */
 639      $minimum_site_name_length = apply_filters( 'minimum_site_name_length', 4 );
 640  
 641      if ( strlen( $blogname ) < $minimum_site_name_length ) {
 642          /* translators: %s: minimum site name length */
 643          $errors->add( 'blogname', sprintf( _n( 'Site name must be at least %s character.', 'Site name must be at least %s characters.', $minimum_site_name_length ), number_format_i18n( $minimum_site_name_length ) ) );
 644      }
 645  
 646      // do not allow users to create a blog that conflicts with a page on the main blog.
 647      if ( ! is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( 'SELECT post_name FROM ' . $wpdb->get_blog_prefix( $current_network->site_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) ) {
 648          $errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
 649      }
 650  
 651      // all numeric?
 652      if ( preg_match( '/^[0-9]*$/', $blogname ) ) {
 653          $errors->add( 'blogname', __( 'Sorry, site names must have letters too!' ) );
 654      }
 655  
 656      /**
 657       * Filters the new site name during registration.
 658       *
 659       * The name is the site's subdomain or the site's subdirectory
 660       * path depending on the network settings.
 661       *
 662       * @since MU (3.0.0)
 663       *
 664       * @param string $blogname Site name.
 665       */
 666      $blogname = apply_filters( 'newblogname', $blogname );
 667  
 668      $blog_title = wp_unslash( $blog_title );
 669  
 670      if ( empty( $blog_title ) ) {
 671          $errors->add( 'blog_title', __( 'Please enter a site title.' ) );
 672      }
 673  
 674      // Check if the domain/path has been used already.
 675      if ( is_subdomain_install() ) {
 676          $mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
 677          $path     = $base;
 678      } else {
 679          $mydomain = "$domain";
 680          $path     = $base . $blogname . '/';
 681      }
 682      if ( domain_exists( $mydomain, $path, $current_network->id ) ) {
 683          $errors->add( 'blogname', __( 'Sorry, that site already exists!' ) );
 684      }
 685  
 686      if ( username_exists( $blogname ) ) {
 687          if ( ! is_object( $user ) || ( is_object( $user ) && ( $user->user_login != $blogname ) ) ) {
 688              $errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
 689          }
 690      }
 691  
 692      // Has someone already signed up for this domain?
 693      $signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path ) ); // TODO: Check email too?
 694      if ( ! empty( $signup ) ) {
 695          $diff = time() - mysql2date( 'U', $signup->registered );
 696          // If registered more than two days ago, cancel registration and let this signup go through.
 697          if ( $diff > 2 * DAY_IN_SECONDS ) {
 698              $wpdb->delete(
 699                  $wpdb->signups,
 700                  array(
 701                      'domain' => $mydomain,
 702                      'path'   => $path,
 703                  )
 704              );
 705          } else {
 706              $errors->add( 'blogname', __( 'That site is currently reserved but may be available in a couple days.' ) );
 707          }
 708      }
 709  
 710      $result = array(
 711          'domain'     => $mydomain,
 712          'path'       => $path,
 713          'blogname'   => $blogname,
 714          'blog_title' => $blog_title,
 715          'user'       => $user,
 716          'errors'     => $errors,
 717      );
 718  
 719      /**
 720       * Filters site details and error messages following registration.
 721       *
 722       * @since MU (3.0.0)
 723       *
 724       * @param array $result {
 725       *     Array of domain, path, blog name, blog title, user and error messages.
 726       *
 727       *     @type string         $domain     Domain for the site.
 728       *     @type string         $path       Path for the site. Used in subdirectory installations.
 729       *     @type string         $blogname   The unique site name (slug).
 730       *     @type string         $blog_title Blog title.
 731       *     @type string|WP_User $user       By default, an empty string. A user object if provided.
 732       *     @type WP_Error       $errors     WP_Error containing any errors found.
 733       * }
 734       */
 735      return apply_filters( 'wpmu_validate_blog_signup', $result );
 736  }
 737  
 738  /**
 739   * Record site signup information for future activation.
 740   *
 741   * @since MU (3.0.0)
 742   *
 743   * @global wpdb $wpdb WordPress database abstraction object.
 744   *
 745   * @param string $domain     The requested domain.
 746   * @param string $path       The requested path.
 747   * @param string $title      The requested site title.
 748   * @param string $user       The user's requested login name.
 749   * @param string $user_email The user's email address.
 750   * @param array  $meta       Optional. Signup meta data. By default, contains the requested privacy setting and lang_id.
 751   */
 752  function wpmu_signup_blog( $domain, $path, $title, $user, $user_email, $meta = array() ) {
 753      global $wpdb;
 754  
 755      $key = substr( md5( time() . wp_rand() . $domain ), 0, 16 );
 756  
 757      /**
 758       * Filters the metadata for a site signup.
 759       *
 760       * The metadata will be serialized prior to storing it in the database.
 761       *
 762       * @since 4.8.0
 763       *
 764       * @param array  $meta       Signup meta data. Default empty array.
 765       * @param string $domain     The requested domain.
 766       * @param string $path       The requested path.
 767       * @param string $title      The requested site title.
 768       * @param string $user       The user's requested login name.
 769       * @param string $user_email The user's email address.
 770       * @param string $key        The user's activation key.
 771       */
 772      $meta = apply_filters( 'signup_site_meta', $meta, $domain, $path, $title, $user, $user_email, $key );
 773  
 774      $wpdb->insert(
 775          $wpdb->signups,
 776          array(
 777              'domain'         => $domain,
 778              'path'           => $path,
 779              'title'          => $title,
 780              'user_login'     => $user,
 781              'user_email'     => $user_email,
 782              'registered'     => current_time( 'mysql', true ),
 783              'activation_key' => $key,
 784              'meta'           => serialize( $meta ),
 785          )
 786      );
 787  
 788      /**
 789       * Fires after site signup information has been written to the database.
 790       *
 791       * @since 4.4.0
 792       *
 793       * @param string $domain     The requested domain.
 794       * @param string $path       The requested path.
 795       * @param string $title      The requested site title.
 796       * @param string $user       The user's requested login name.
 797       * @param string $user_email The user's email address.
 798       * @param string $key        The user's activation key.
 799       * @param array  $meta       Signup meta data. By default, contains the requested privacy setting and lang_id.
 800       */
 801      do_action( 'after_signup_site', $domain, $path, $title, $user, $user_email, $key, $meta );
 802  }
 803  
 804  /**
 805   * Record user signup information for future activation.
 806   *
 807   * This function is used when user registration is open but
 808   * new site registration is not.
 809   *
 810   * @since MU (3.0.0)
 811   *
 812   * @global wpdb $wpdb WordPress database abstraction object.
 813   *
 814   * @param string $user       The user's requested login name.
 815   * @param string $user_email The user's email address.
 816   * @param array  $meta       Optional. Signup meta data. Default empty array.
 817   */
 818  function wpmu_signup_user( $user, $user_email, $meta = array() ) {
 819      global $wpdb;
 820  
 821      // Format data
 822      $user       = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
 823      $user_email = sanitize_email( $user_email );
 824      $key        = substr( md5( time() . wp_rand() . $user_email ), 0, 16 );
 825  
 826      /**
 827       * Filters the metadata for a user signup.
 828       *
 829       * The metadata will be serialized prior to storing it in the database.
 830       *
 831       * @since 4.8.0
 832       *
 833       * @param array  $meta       Signup meta data. Default empty array.
 834       * @param string $user       The user's requested login name.
 835       * @param string $user_email The user's email address.
 836       * @param string $key        The user's activation key.
 837       */
 838      $meta = apply_filters( 'signup_user_meta', $meta, $user, $user_email, $key );
 839  
 840      $wpdb->insert(
 841          $wpdb->signups,
 842          array(
 843              'domain'         => '',
 844              'path'           => '',
 845              'title'          => '',
 846              'user_login'     => $user,
 847              'user_email'     => $user_email,
 848              'registered'     => current_time( 'mysql', true ),
 849              'activation_key' => $key,
 850              'meta'           => serialize( $meta ),
 851          )
 852      );
 853  
 854      /**
 855       * Fires after a user's signup information has been written to the database.
 856       *
 857       * @since 4.4.0
 858       *
 859       * @param string $user       The user's requested login name.
 860       * @param string $user_email The user's email address.
 861       * @param string $key        The user's activation key.
 862       * @param array  $meta       Signup meta data. Default empty array.
 863       */
 864      do_action( 'after_signup_user', $user, $user_email, $key, $meta );
 865  }
 866  
 867  /**
 868   * Send a confirmation request email to a user when they sign up for a new site. The new site will not become active
 869   * until the confirmation link is clicked.
 870   *
 871   * This is the notification function used when site registration
 872   * is enabled.
 873   *
 874   * Filter {@see 'wpmu_signup_blog_notification'} to bypass this function or
 875   * replace it with your own notification behavior.
 876   *
 877   * Filter {@see 'wpmu_signup_blog_notification_email'} and
 878   * {@see 'wpmu_signup_blog_notification_subject'} to change the content
 879   * and subject line of the email sent to newly registered users.
 880   *
 881   * @since MU (3.0.0)
 882   *
 883   * @param string $domain     The new blog domain.
 884   * @param string $path       The new blog path.
 885   * @param string $title      The site title.
 886   * @param string $user_login The user's login name.
 887   * @param string $user_email The user's email address.
 888   * @param string $key        The activation key created in wpmu_signup_blog()
 889   * @param array  $meta       Optional. Signup meta data. By default, contains the requested privacy setting and lang_id.
 890   * @return bool
 891   */
 892  function wpmu_signup_blog_notification( $domain, $path, $title, $user_login, $user_email, $key, $meta = array() ) {
 893      /**
 894       * Filters whether to bypass the new site email notification.
 895       *
 896       * @since MU (3.0.0)
 897       *
 898       * @param string|bool $domain     Site domain.
 899       * @param string      $path       Site path.
 900       * @param string      $title      Site title.
 901       * @param string      $user_login User login name.
 902       * @param string      $user_email User email address.
 903       * @param string      $key        Activation key created in wpmu_signup_blog().
 904       * @param array       $meta       Signup meta data. By default, contains the requested privacy setting and lang_id.
 905       */
 906      if ( ! apply_filters( 'wpmu_signup_blog_notification', $domain, $path, $title, $user_login, $user_email, $key, $meta ) ) {
 907          return false;
 908      }
 909  
 910      // Send email with activation link.
 911      if ( ! is_subdomain_install() || get_current_network_id() != 1 ) {
 912          $activate_url = network_site_url( "wp-activate.php?key=$key" );
 913      } else {
 914          $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API
 915      }
 916  
 917      $activate_url = esc_url( $activate_url );
 918      $admin_email  = get_site_option( 'admin_email' );
 919      if ( $admin_email == '' ) {
 920          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
 921      }
 922      $from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
 923      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
 924  
 925      $user            = get_user_by( 'login', $user_login );
 926      $switched_locale = switch_to_locale( get_user_locale( $user ) );
 927  
 928      $message = sprintf(
 929          /**
 930           * Filters the message content of the new blog notification email.
 931           *
 932           * Content should be formatted for transmission via wp_mail().
 933           *
 934           * @since MU (3.0.0)
 935           *
 936           * @param string $content    Content of the notification email.
 937           * @param string $domain     Site domain.
 938           * @param string $path       Site path.
 939           * @param string $title      Site title.
 940           * @param string $user_login User login name.
 941           * @param string $user_email User email address.
 942           * @param string $key        Activation key created in wpmu_signup_blog().
 943           * @param array  $meta       Signup meta data. By default, contains the requested privacy setting and lang_id.
 944           */
 945          apply_filters(
 946              'wpmu_signup_blog_notification_email',
 947              __( "To activate your blog, please click the following link:\n\n%1\$s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your site here:\n\n%2\$s" ),
 948              $domain,
 949              $path,
 950              $title,
 951              $user_login,
 952              $user_email,
 953              $key,
 954              $meta
 955          ),
 956          $activate_url,
 957          esc_url( "http://{$domain}{$path}" ),
 958          $key
 959      );
 960      // TODO: Don't hard code activation link.
 961      $subject = sprintf(
 962          /**
 963           * Filters the subject of the new blog notification email.
 964           *
 965           * @since MU (3.0.0)
 966           *
 967           * @param string $subject    Subject of the notification email.
 968           * @param string $domain     Site domain.
 969           * @param string $path       Site path.
 970           * @param string $title      Site title.
 971           * @param string $user_login User login name.
 972           * @param string $user_email User email address.
 973           * @param string $key        Activation key created in wpmu_signup_blog().
 974           * @param array  $meta       Signup meta data. By default, contains the requested privacy setting and lang_id.
 975           */
 976          apply_filters(
 977              'wpmu_signup_blog_notification_subject',
 978              /* translators: New site notification email subject. 1: Network name, 2: New site URL */
 979              _x( '[%1$s] Activate %2$s', 'New site notification email subject' ),
 980              $domain,
 981              $path,
 982              $title,
 983              $user_login,
 984              $user_email,
 985              $key,
 986              $meta
 987          ),
 988          $from_name,
 989          esc_url( 'http://' . $domain . $path )
 990      );
 991      wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
 992  
 993      if ( $switched_locale ) {
 994          restore_previous_locale();
 995      }
 996  
 997      return true;
 998  }
 999  
1000  /**
1001   * Send a confirmation request email to a user when they sign up for a new user account (without signing up for a site
1002   * at the same time). The user account will not become active until the confirmation link is clicked.
1003   *
1004   * This is the notification function used when no new site has
1005   * been requested.
1006   *
1007   * Filter {@see 'wpmu_signup_user_notification'} to bypass this function or
1008   * replace it with your own notification behavior.
1009   *
1010   * Filter {@see 'wpmu_signup_user_notification_email'} and
1011   * {@see 'wpmu_signup_user_notification_subject'} to change the content
1012   * and subject line of the email sent to newly registered users.
1013   *
1014   * @since MU (3.0.0)
1015   *
1016   * @param string $user_login The user's login name.
1017   * @param string $user_email The user's email address.
1018   * @param string $key        The activation key created in wpmu_signup_user()
1019   * @param array  $meta       Optional. Signup meta data. Default empty array.
1020   * @return bool
1021   */
1022  function wpmu_signup_user_notification( $user_login, $user_email, $key, $meta = array() ) {
1023      /**
1024       * Filters whether to bypass the email notification for new user sign-up.
1025       *
1026       * @since MU (3.0.0)
1027       *
1028       * @param string $user_login User login name.
1029       * @param string $user_email User email address.
1030       * @param string $key        Activation key created in wpmu_signup_user().
1031       * @param array  $meta       Signup meta data. Default empty array.
1032       */
1033      if ( ! apply_filters( 'wpmu_signup_user_notification', $user_login, $user_email, $key, $meta ) ) {
1034          return false;
1035      }
1036  
1037      $user            = get_user_by( 'login', $user_login );
1038      $switched_locale = switch_to_locale( get_user_locale( $user ) );
1039  
1040      // Send email with activation link.
1041      $admin_email = get_site_option( 'admin_email' );
1042      if ( $admin_email == '' ) {
1043          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1044      }
1045      $from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1046      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
1047      $message         = sprintf(
1048          /**
1049           * Filters the content of the notification email for new user sign-up.
1050           *
1051           * Content should be formatted for transmission via wp_mail().
1052           *
1053           * @since MU (3.0.0)
1054           *
1055           * @param string $content    Content of the notification email.
1056           * @param string $user_login User login name.
1057           * @param string $user_email User email address.
1058           * @param string $key        Activation key created in wpmu_signup_user().
1059           * @param array  $meta       Signup meta data. Default empty array.
1060           */
1061          apply_filters(
1062              'wpmu_signup_user_notification_email',
1063              __( "To activate your user, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login." ),
1064              $user_login,
1065              $user_email,
1066              $key,
1067              $meta
1068          ),
1069          site_url( "wp-activate.php?key=$key" )
1070      );
1071      // TODO: Don't hard code activation link.
1072      $subject = sprintf(
1073          /**
1074           * Filters the subject of the notification email of new user signup.
1075           *
1076           * @since MU (3.0.0)
1077           *
1078           * @param string $subject    Subject of the notification email.
1079           * @param string $user_login User login name.
1080           * @param string $user_email User email address.
1081           * @param string $key        Activation key created in wpmu_signup_user().
1082           * @param array  $meta       Signup meta data. Default empty array.
1083           */
1084          apply_filters(
1085              'wpmu_signup_user_notification_subject',
1086              /* translators: New user notification email subject. 1: Network name, 2: New user login */
1087              _x( '[%1$s] Activate %2$s', 'New user notification email subject' ),
1088              $user_login,
1089              $user_email,
1090              $key,
1091              $meta
1092          ),
1093          $from_name,
1094          $user_login
1095      );
1096      wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
1097  
1098      if ( $switched_locale ) {
1099          restore_previous_locale();
1100      }
1101  
1102      return true;
1103  }
1104  
1105  /**
1106   * Activate a signup.
1107   *
1108   * Hook to {@see 'wpmu_activate_user'} or {@see 'wpmu_activate_blog'} for events
1109   * that should happen only when users or sites are self-created (since
1110   * those actions are not called when users and sites are created
1111   * by a Super Admin).
1112   *
1113   * @since MU (3.0.0)
1114   *
1115   * @global wpdb $wpdb WordPress database abstraction object.
1116   *
1117   * @param string $key The activation key provided to the user.
1118   * @return array|WP_Error An array containing information about the activated user and/or blog
1119   */
1120  function wpmu_activate_signup( $key ) {
1121      global $wpdb;
1122  
1123      $signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key ) );
1124  
1125      if ( empty( $signup ) ) {
1126          return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) );
1127      }
1128  
1129      if ( $signup->active ) {
1130          if ( empty( $signup->domain ) ) {
1131              return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup );
1132          } else {
1133              return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup );
1134          }
1135      }
1136  
1137      $meta     = maybe_unserialize( $signup->meta );
1138      $password = wp_generate_password( 12, false );
1139  
1140      $user_id = username_exists( $signup->user_login );
1141  
1142      if ( ! $user_id ) {
1143          $user_id = wpmu_create_user( $signup->user_login, $password, $signup->user_email );
1144      } else {
1145          $user_already_exists = true;
1146      }
1147  
1148      if ( ! $user_id ) {
1149          return new WP_Error( 'create_user', __( 'Could not create user' ), $signup );
1150      }
1151  
1152      $now = current_time( 'mysql', true );
1153  
1154      if ( empty( $signup->domain ) ) {
1155          $wpdb->update(
1156              $wpdb->signups,
1157              array(
1158                  'active'    => 1,
1159                  'activated' => $now,
1160              ),
1161              array( 'activation_key' => $key )
1162          );
1163  
1164          if ( isset( $user_already_exists ) ) {
1165              return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup );
1166          }
1167  
1168          /**
1169           * Fires immediately after a new user is activated.
1170           *
1171           * @since MU (3.0.0)
1172           *
1173           * @param int   $user_id  User ID.
1174           * @param int   $password User password.
1175           * @param array $meta     Signup meta data.
1176           */
1177          do_action( 'wpmu_activate_user', $user_id, $password, $meta );
1178          return array(
1179              'user_id'  => $user_id,
1180              'password' => $password,
1181              'meta'     => $meta,
1182          );
1183      }
1184  
1185      $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, get_current_network_id() );
1186  
1187      // TODO: What to do if we create a user but cannot create a blog?
1188      if ( is_wp_error( $blog_id ) ) {
1189          // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
1190          // setting the activation flag. Let's just set the active flag and instruct the user to reset their password.
1191          if ( 'blog_taken' == $blog_id->get_error_code() ) {
1192              $blog_id->add_data( $signup );
1193              $wpdb->update(
1194                  $wpdb->signups,
1195                  array(
1196                      'active'    => 1,
1197                      'activated' => $now,
1198                  ),
1199                  array( 'activation_key' => $key )
1200              );
1201          }
1202          return $blog_id;
1203      }
1204  
1205      $wpdb->update(
1206          $wpdb->signups,
1207          array(
1208              'active'    => 1,
1209              'activated' => $now,
1210          ),
1211          array( 'activation_key' => $key )
1212      );
1213      /**
1214       * Fires immediately after a site is activated.
1215       *
1216       * @since MU (3.0.0)
1217       *
1218       * @param int    $blog_id       Blog ID.
1219       * @param int    $user_id       User ID.
1220       * @param int    $password      User password.
1221       * @param string $signup_title  Site title.
1222       * @param array  $meta          Signup meta data. By default, contains the requested privacy setting and lang_id.
1223       */
1224      do_action( 'wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta );
1225  
1226      return array(
1227          'blog_id'  => $blog_id,
1228          'user_id'  => $user_id,
1229          'password' => $password,
1230          'title'    => $signup->title,
1231          'meta'     => $meta,
1232      );
1233  }
1234  
1235  /**
1236   * Create a user.
1237   *
1238   * This function runs when a user self-registers as well as when
1239   * a Super Admin creates a new user. Hook to {@see 'wpmu_new_user'} for events
1240   * that should affect all new users, but only on Multisite (otherwise
1241   * use {@see'user_register'}).
1242   *
1243   * @since MU (3.0.0)
1244   *
1245   * @param string $user_name The new user's login name.
1246   * @param string $password  The new user's password.
1247   * @param string $email     The new user's email address.
1248   * @return int|false Returns false on failure, or int $user_id on success
1249   */
1250  function wpmu_create_user( $user_name, $password, $email ) {
1251      $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
1252  
1253      $user_id = wp_create_user( $user_name, $password, $email );
1254      if ( is_wp_error( $user_id ) ) {
1255          return false;
1256      }
1257  
1258      // Newly created users have no roles or caps until they are added to a blog.
1259      delete_user_option( $user_id, 'capabilities' );
1260      delete_user_option( $user_id, 'user_level' );
1261  
1262      /**
1263       * Fires immediately after a new user is created.
1264       *
1265       * @since MU (3.0.0)
1266       *
1267       * @param int $user_id User ID.
1268       */
1269      do_action( 'wpmu_new_user', $user_id );
1270  
1271      return $user_id;
1272  }
1273  
1274  /**
1275   * Create a site.
1276   *
1277   * This function runs when a user self-registers a new site as well
1278   * as when a Super Admin creates a new site. Hook to {@see 'wpmu_new_blog'}
1279   * for events that should affect all new sites.
1280   *
1281   * On subdirectory installations, $domain is the same as the main site's
1282   * domain, and the path is the subdirectory name (eg 'example.com'
1283   * and '/blog1/'). On subdomain installations, $domain is the new subdomain +
1284   * root domain (eg 'blog1.example.com'), and $path is '/'.
1285   *
1286   * @since MU (3.0.0)
1287   *
1288   * @param string $domain     The new site's domain.
1289   * @param string $path       The new site's path.
1290   * @param string $title      The new site's title.
1291   * @param int    $user_id    The user ID of the new site's admin.
1292   * @param array  $options    Optional. Array of key=>value pairs used to set initial site options.
1293   *                           If valid status keys are included ('public', 'archived', 'mature',
1294   *                           'spam', 'deleted', or 'lang_id') the given site status(es) will be
1295   *                           updated. Otherwise, keys and values will be used to set options for
1296   *                           the new site. Default empty array.
1297   * @param int    $network_id Optional. Network ID. Only relevant on multi-network installations.
1298   * @return int|WP_Error Returns WP_Error object on failure, the new site ID on success.
1299   */
1300  function wpmu_create_blog( $domain, $path, $title, $user_id, $options = array(), $network_id = 1 ) {
1301      $defaults = array(
1302          'public' => 0,
1303      );
1304      $options  = wp_parse_args( $options, $defaults );
1305  
1306      $title   = strip_tags( $title );
1307      $user_id = (int) $user_id;
1308  
1309      // Check if the domain has been used already. We should return an error message.
1310      if ( domain_exists( $domain, $path, $network_id ) ) {
1311          return new WP_Error( 'blog_taken', __( 'Sorry, that site already exists!' ) );
1312      }
1313  
1314      if ( ! wp_installing() ) {
1315          wp_installing( true );
1316      }
1317  
1318      $site_data_whitelist = array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' );
1319  
1320      $site_data = array_merge(
1321          array(
1322              'domain'     => $domain,
1323              'path'       => $path,
1324              'network_id' => $network_id,
1325          ),
1326          array_intersect_key( $options, array_flip( $site_data_whitelist ) )
1327      );
1328  
1329      // Data to pass to wp_initialize_site().
1330      $site_initialization_data = array(
1331          'title'   => $title,
1332          'user_id' => $user_id,
1333          'options' => array_diff_key( $options, array_flip( $site_data_whitelist ) ),
1334      );
1335  
1336      $blog_id = wp_insert_site( array_merge( $site_data, $site_initialization_data ) );
1337  
1338      if ( is_wp_error( $blog_id ) ) {
1339          return $blog_id;
1340      }
1341  
1342      wp_cache_set( 'last_changed', microtime(), 'sites' );
1343  
1344      return $blog_id;
1345  }
1346  
1347  /**
1348   * Notifies the network admin that a new site has been activated.
1349   *
1350   * Filter {@see 'newblog_notify_siteadmin'} to change the content of
1351   * the notification email.
1352   *
1353   * @since MU (3.0.0)
1354   * @since 5.1.0 $blog_id now supports input from the {@see 'wp_initialize_site'} action.
1355   *
1356   * @param WP_Site|int $blog_id    The new site's object or ID.
1357   * @param string      $deprecated Not used.
1358   * @return bool
1359   */
1360  function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
1361      if ( is_object( $blog_id ) ) {
1362          $blog_id = $blog_id->blog_id;
1363      }
1364  
1365      if ( get_site_option( 'registrationnotification' ) != 'yes' ) {
1366          return false;
1367      }
1368  
1369      $email = get_site_option( 'admin_email' );
1370      if ( is_email( $email ) == false ) {
1371          return false;
1372      }
1373  
1374      $options_site_url = esc_url( network_admin_url( 'settings.php' ) );
1375  
1376      switch_to_blog( $blog_id );
1377      $blogname = get_option( 'blogname' );
1378      $siteurl  = site_url();
1379      restore_current_blog();
1380  
1381      /* translators: New site notification email. 1: Site URL, 2: User IP address, 3: Settings screen URL */
1382      $msg = sprintf(
1383          __(
1384              'New Site: %1$s
1385  URL: %2$s
1386  Remote IP address: %3$s
1387  
1388  Disable these notifications: %4$s'
1389          ),
1390          $blogname,
1391          $siteurl,
1392          wp_unslash( $_SERVER['REMOTE_ADDR'] ),
1393          $options_site_url
1394      );
1395      /**
1396       * Filters the message body of the new site activation email sent
1397       * to the network administrator.
1398       *
1399       * @since MU (3.0.0)
1400       *
1401       * @param string $msg Email body.
1402       */
1403      $msg = apply_filters( 'newblog_notify_siteadmin', $msg );
1404  
1405      wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg );
1406      return true;
1407  }
1408  
1409  /**
1410   * Notifies the network admin that a new user has been activated.
1411   *
1412   * Filter {@see 'newuser_notify_siteadmin'} to change the content of
1413   * the notification email.
1414   *
1415   * @since MU (3.0.0)
1416   *
1417   * @param int $user_id The new user's ID.
1418   * @return bool
1419   */
1420  function newuser_notify_siteadmin( $user_id ) {
1421      if ( get_site_option( 'registrationnotification' ) != 'yes' ) {
1422          return false;
1423      }
1424  
1425      $email = get_site_option( 'admin_email' );
1426  
1427      if ( is_email( $email ) == false ) {
1428          return false;
1429      }
1430  
1431      $user = get_userdata( $user_id );
1432  
1433      $options_site_url = esc_url( network_admin_url( 'settings.php' ) );
1434      /* translators: New user notification email. 1: User login, 2: User IP address, 3: Settings screen URL */
1435      $msg = sprintf(
1436          __(
1437              'New User: %1$s
1438  Remote IP address: %2$s
1439  
1440  Disable these notifications: %3$s'
1441          ),
1442          $user->user_login,
1443          wp_unslash( $_SERVER['REMOTE_ADDR'] ),
1444          $options_site_url
1445      );
1446  
1447      /**
1448       * Filters the message body of the new user activation email sent
1449       * to the network administrator.
1450       *
1451       * @since MU (3.0.0)
1452       *
1453       * @param string  $msg  Email body.
1454       * @param WP_User $user WP_User instance of the new user.
1455       */
1456      $msg = apply_filters( 'newuser_notify_siteadmin', $msg, $user );
1457      wp_mail( $email, sprintf( __( 'New User Registration: %s' ), $user->user_login ), $msg );
1458      return true;
1459  }
1460  
1461  /**
1462   * Checks whether a site name is already taken.
1463   *
1464   * The name is the site's subdomain or the site's subdirectory
1465   * path depending on the network settings.
1466   *
1467   * Used during the new site registration process to ensure
1468   * that each site name is unique.
1469   *
1470   * @since MU (3.0.0)
1471   *
1472   * @param string $domain     The domain to be checked.
1473   * @param string $path       The path to be checked.
1474   * @param int    $network_id Optional. Network ID. Relevant only on multi-network installations.
1475   * @return int|null The site ID if the site name exists, null otherwise.
1476   */
1477  function domain_exists( $domain, $path, $network_id = 1 ) {
1478      $path   = trailingslashit( $path );
1479      $args   = array(
1480          'network_id'             => $network_id,
1481          'domain'                 => $domain,
1482          'path'                   => $path,
1483          'fields'                 => 'ids',
1484          'number'                 => 1,
1485          'update_site_meta_cache' => false,
1486      );
1487      $result = get_sites( $args );
1488      $result = array_shift( $result );
1489  
1490      /**
1491       * Filters whether a site name is taken.
1492       *
1493       * The name is the site's subdomain or the site's subdirectory
1494       * path depending on the network settings.
1495       *
1496       * @since 3.5.0
1497       *
1498       * @param int|null $result     The site ID if the site name exists, null otherwise.
1499       * @param string   $domain     Domain to be checked.
1500       * @param string   $path       Path to be checked.
1501       * @param int      $network_id Network ID. Relevant only on multi-network installations.
1502       */
1503      return apply_filters( 'domain_exists', $result, $domain, $path, $network_id );
1504  }
1505  
1506  /**
1507   * Notify a user that their blog activation has been successful.
1508   *
1509   * Filter {@see 'wpmu_welcome_notification'} to disable or bypass.
1510   *
1511   * Filter {@see 'update_welcome_email'} and {@see 'update_welcome_subject'} to
1512   * modify the content and subject line of the notification email.
1513   *
1514   * @since MU (3.0.0)
1515   *
1516   * @param int    $blog_id  Blog ID.
1517   * @param int    $user_id  User ID.
1518   * @param string $password User password.
1519   * @param string $title    Site title.
1520   * @param array  $meta     Optional. Signup meta data. By default, contains the requested privacy setting and lang_id.
1521   * @return bool
1522   */
1523  function wpmu_welcome_notification( $blog_id, $user_id, $password, $title, $meta = array() ) {
1524      $current_network = get_network();
1525  
1526      /**
1527       * Filters whether to bypass the welcome email after site activation.
1528       *
1529       * Returning false disables the welcome email.
1530       *
1531       * @since MU (3.0.0)
1532       *
1533       * @param int|bool $blog_id  Blog ID.
1534       * @param int      $user_id  User ID.
1535       * @param string   $password User password.
1536       * @param string   $title    Site title.
1537       * @param array    $meta     Signup meta data. By default, contains the requested privacy setting and lang_id.
1538       */
1539      if ( ! apply_filters( 'wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta ) ) {
1540          return false;
1541      }
1542  
1543      $user = get_userdata( $user_id );
1544  
1545      $switched_locale = switch_to_locale( get_user_locale( $user ) );
1546  
1547      $welcome_email = get_site_option( 'welcome_email' );
1548      if ( $welcome_email == false ) {
1549          /* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
1550          $welcome_email = __(
1551              'Howdy USERNAME,
1552  
1553  Your new SITE_NAME site has been successfully set up at:
1554  BLOG_URL
1555  
1556  You can log in to the administrator account with the following information:
1557  
1558  Username: USERNAME
1559  Password: PASSWORD
1560  Log in here: BLOG_URLwp-login.php
1561  
1562  We hope you enjoy your new site. Thanks!
1563  
1564  --The Team @ SITE_NAME'
1565          );
1566      }
1567  
1568      $url = get_blogaddress_by_id( $blog_id );
1569  
1570      $welcome_email = str_replace( 'SITE_NAME', $current_network->site_name, $welcome_email );
1571      $welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
1572      $welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email );
1573      $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1574      $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1575  
1576      /**
1577       * Filters the content of the welcome email after site activation.
1578       *
1579       * Content should be formatted for transmission via wp_mail().
1580       *
1581       * @since MU (3.0.0)
1582       *
1583       * @param string $welcome_email Message body of the email.
1584       * @param int    $blog_id       Blog ID.
1585       * @param int    $user_id       User ID.
1586       * @param string $password      User password.
1587       * @param string $title         Site title.
1588       * @param array  $meta          Signup meta data. By default, contains the requested privacy setting and lang_id.
1589       */
1590      $welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta );
1591      $admin_email   = get_site_option( 'admin_email' );
1592  
1593      if ( $admin_email == '' ) {
1594          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1595      }
1596  
1597      $from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1598      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
1599      $message         = $welcome_email;
1600  
1601      if ( empty( $current_network->site_name ) ) {
1602          $current_network->site_name = 'WordPress';
1603      }
1604  
1605      /* translators: New site notification email subject. 1: Network name, 2: New site name */
1606      $subject = __( 'New %1$s Site: %2$s' );
1607  
1608      /**
1609       * Filters the subject of the welcome email after site activation.
1610       *
1611       * @since MU (3.0.0)
1612       *
1613       * @param string $subject Subject of the email.
1614       */
1615      $subject = apply_filters( 'update_welcome_subject', sprintf( $subject, $current_network->site_name, wp_unslash( $title ) ) );
1616      wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
1617  
1618      if ( $switched_locale ) {
1619          restore_previous_locale();
1620      }
1621  
1622      return true;
1623  }
1624  
1625  /**
1626   * Notify a user that their account activation has been successful.
1627   *
1628   * Filter {@see 'wpmu_welcome_user_notification'} to disable or bypass.
1629   *
1630   * Filter {@see 'update_welcome_user_email'} and {@see 'update_welcome_user_subject'} to
1631   * modify the content and subject line of the notification email.
1632   *
1633   * @since MU (3.0.0)
1634   *
1635   * @param int    $user_id  User ID.
1636   * @param string $password User password.
1637   * @param array  $meta     Optional. Signup meta data. Default empty array.
1638   * @return bool
1639   */
1640  function wpmu_welcome_user_notification( $user_id, $password, $meta = array() ) {
1641      $current_network = get_network();
1642  
1643      /**
1644       * Filters whether to bypass the welcome email after user activation.
1645       *
1646       * Returning false disables the welcome email.
1647       *
1648       * @since MU (3.0.0)
1649       *
1650       * @param int    $user_id  User ID.
1651       * @param string $password User password.
1652       * @param array  $meta     Signup meta data. Default empty array.
1653       */
1654      if ( ! apply_filters( 'wpmu_welcome_user_notification', $user_id, $password, $meta ) ) {
1655          return false;
1656      }
1657  
1658      $welcome_email = get_site_option( 'welcome_user_email' );
1659  
1660      $user = get_userdata( $user_id );
1661  
1662      $switched_locale = switch_to_locale( get_user_locale( $user ) );
1663  
1664      /**
1665       * Filters the content of the welcome email after user activation.
1666       *
1667       * Content should be formatted for transmission via wp_mail().
1668       *
1669       * @since MU (3.0.0)
1670       *
1671       * @param string $welcome_email The message body of the account activation success email.
1672       * @param int    $user_id       User ID.
1673       * @param string $password      User password.
1674       * @param array  $meta          Signup meta data. Default empty array.
1675       */
1676      $welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta );
1677      $welcome_email = str_replace( 'SITE_NAME', $current_network->site_name, $welcome_email );
1678      $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email );
1679      $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email );
1680      $welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email );
1681  
1682      $admin_email = get_site_option( 'admin_email' );
1683  
1684      if ( $admin_email == '' ) {
1685          $admin_email = 'support@' . $_SERVER['SERVER_NAME'];
1686      }
1687  
1688      $from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
1689      $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . 'Content-Type: text/plain; charset="' . get_option( 'blog_charset' ) . "\"\n";
1690      $message         = $welcome_email;
1691  
1692      if ( empty( $current_network->site_name ) ) {
1693          $current_network->site_name = 'WordPress';
1694      }
1695  
1696      /* translators: New user notification email subject. 1: Network name, 2: New user login */
1697      $subject = __( 'New %1$s User: %2$s' );
1698  
1699      /**
1700       * Filters the subject of the welcome email after user activation.
1701       *
1702       * @since MU (3.0.0)
1703       *
1704       * @param string $subject Subject of the email.
1705       */
1706      $subject = apply_filters( 'update_welcome_user_subject', sprintf( $subject, $current_network->site_name, $user->user_login ) );
1707      wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
1708  
1709      if ( $switched_locale ) {
1710          restore_previous_locale();
1711      }
1712  
1713      return true;
1714  }
1715  
1716  /**
1717   * Get the current network.
1718   *
1719   * Returns an object containing the 'id', 'domain', 'path', and 'site_name'
1720   * properties of the network being viewed.
1721   *
1722   * @see wpmu_current_site()
1723   *
1724   * @since MU (3.0.0)
1725   *
1726   * @global WP_Network $current_site
1727   *
1728   * @return WP_Network
1729   */
1730  function get_current_site() {
1731      global $current_site;
1732      return $current_site;
1733  }
1734  
1735  /**
1736   * Get a user's most recent post.
1737   *
1738   * Walks through each of a user's blogs to find the post with
1739   * the most recent post_date_gmt.
1740   *
1741   * @since MU (3.0.0)
1742   *
1743   * @global wpdb $wpdb WordPress database abstraction object.
1744   *
1745   * @param int $user_id
1746   * @return array Contains the blog_id, post_id, post_date_gmt, and post_gmt_ts
1747   */
1748  function get_most_recent_post_of_user( $user_id ) {
1749      global $wpdb;
1750  
1751      $user_blogs       = get_blogs_of_user( (int) $user_id );
1752      $most_recent_post = array();
1753  
1754      // Walk through each blog and get the most recent post
1755      // published by $user_id
1756      foreach ( (array) $user_blogs as $blog ) {
1757          $prefix      = $wpdb->get_blog_prefix( $blog->userblog_id );
1758          $recent_post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A );
1759  
1760          // Make sure we found a post
1761          if ( isset( $recent_post['ID'] ) ) {
1762              $post_gmt_ts = strtotime( $recent_post['post_date_gmt'] );
1763  
1764              // If this is the first post checked or if this post is
1765              // newer than the current recent post, make it the new
1766              // most recent post.
1767              if ( ! isset( $most_recent_post['post_gmt_ts'] ) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
1768                  $most_recent_post = array(
1769                      'blog_id'       => $blog->userblog_id,
1770                      'post_id'       => $recent_post['ID'],
1771                      'post_date_gmt' => $recent_post['post_date_gmt'],
1772                      'post_gmt_ts'   => $post_gmt_ts,
1773                  );
1774              }
1775          }
1776      }
1777  
1778      return $most_recent_post;
1779  }
1780  
1781  // Misc functions
1782  
1783  /**
1784   * Check an array of MIME types against a whitelist.
1785   *
1786   * WordPress ships with a set of allowed upload filetypes,
1787   * which is defined in wp-includes/functions.php in
1788   * get_allowed_mime_types(). This function is used to filter
1789   * that list against the filetype whitelist provided by Multisite
1790   * Super Admins at wp-admin/network/settings.php.
1791   *
1792   * @since MU (3.0.0)
1793   *
1794   * @param array $mimes
1795   * @return array
1796   */
1797  function check_upload_mimes( $mimes ) {
1798      $site_exts  = explode( ' ', get_site_option( 'upload_filetypes', 'jpg jpeg png gif' ) );
1799      $site_mimes = array();
1800      foreach ( $site_exts as $ext ) {
1801          foreach ( $mimes as $ext_pattern => $mime ) {
1802              if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false ) {
1803                  $site_mimes[ $ext_pattern ] = $mime;
1804              }
1805          }
1806      }
1807      return $site_mimes;
1808  }
1809  
1810  /**
1811   * Update a blog's post count.
1812   *
1813   * WordPress MS stores a blog's post count as an option so as
1814   * to avoid extraneous COUNTs when a blog's details are fetched
1815   * with get_site(). This function is called when posts are published
1816   * or unpublished to make sure the count stays current.
1817   *
1818   * @since MU (3.0.0)
1819   *
1820   * @global wpdb $wpdb WordPress database abstraction object.
1821   *
1822   * @param string $deprecated Not used.
1823   */
1824  function update_posts_count( $deprecated = '' ) {
1825      global $wpdb;
1826      update_option( 'post_count', (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) );
1827  }
1828  
1829  /**
1830   * Logs the user email, IP, and registration date of a new site.
1831   *
1832   * @since MU (3.0.0)
1833   * @since 5.1.0 Parameters now support input from the {@see 'wp_initialize_site'} action.
1834   *
1835   * @global wpdb $wpdb WordPress database abstraction object.
1836   *
1837   * @param WP_Site|int $blog_id The new site's object or ID.
1838   * @param int|array   $user_id User ID, or array of arguments including 'user_id'.
1839   */
1840  function wpmu_log_new_registrations( $blog_id, $user_id ) {
1841      global $wpdb;
1842  
1843      if ( is_object( $blog_id ) ) {
1844          $blog_id = $blog_id->blog_id;
1845      }
1846  
1847      if ( is_array( $user_id ) ) {
1848          $user_id = ! empty( $user_id['user_id'] ) ? $user_id['user_id'] : 0;
1849      }
1850  
1851      $user = get_userdata( (int) $user_id );
1852      if ( $user ) {
1853          $wpdb->insert(
1854              $wpdb->registration_log,
1855              array(
1856                  'email'           => $user->user_email,
1857                  'IP'              => preg_replace( '/[^0-9., ]/', '', wp_unslash( $_SERVER['REMOTE_ADDR'] ) ),
1858                  'blog_id'         => $blog_id,
1859                  'date_registered' => current_time( 'mysql' ),
1860              )
1861          );
1862      }
1863  }
1864  
1865  /**
1866   * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table.
1867   *
1868   * @since 3.0.0
1869   *
1870   * @see term_id_filter
1871   *
1872   * @global wpdb $wpdb WordPress database abstraction object.
1873   * @staticvar int $global_terms_recurse
1874   *
1875   * @param int    $term_id    An ID for a term on the current blog.
1876   * @param string $deprecated Not used.
1877   * @return int An ID from the global terms table mapped from $term_id.
1878   */
1879  function global_terms( $term_id, $deprecated = '' ) {
1880      global $wpdb;
1881      static $global_terms_recurse = null;
1882  
1883      if ( ! global_terms_enabled() ) {
1884          return $term_id;
1885      }
1886  
1887      // prevent a race condition
1888      $recurse_start = false;
1889      if ( $global_terms_recurse === null ) {
1890          $recurse_start        = true;
1891          $global_terms_recurse = 1;
1892      } elseif ( 10 < $global_terms_recurse++ ) {
1893          return $term_id;
1894      }
1895  
1896      $term_id = intval( $term_id );
1897      $c       = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
1898  
1899      $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
1900      if ( $global_id == null ) {
1901          $used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) );
1902          if ( null == $used_global_id ) {
1903              $wpdb->insert(
1904                  $wpdb->sitecategories,
1905                  array(
1906                      'cat_ID'            => $term_id,
1907                      'cat_name'          => $c->name,
1908                      'category_nicename' => $c->slug,
1909                  )
1910              );
1911              $global_id = $wpdb->insert_id;
1912              if ( empty( $global_id ) ) {
1913                  return $term_id;
1914              }
1915          } else {
1916              $max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" );
1917              $max_local_id  = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
1918              $new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 );
1919              $wpdb->insert(
1920                  $wpdb->sitecategories,
1921                  array(
1922                      'cat_ID'            => $new_global_id,
1923                      'cat_name'          => $c->name,
1924                      'category_nicename' => $c->slug,
1925                  )
1926              );
1927              $global_id = $wpdb->insert_id;
1928          }
1929      } elseif ( $global_id != $term_id ) {
1930          $local_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE term_id = %d", $global_id ) );
1931          if ( null != $local_id ) {
1932              global_terms( $local_id );
1933              if ( 10 < $global_terms_recurse ) {
1934                  $global_id = $term_id;
1935              }
1936          }
1937      }
1938  
1939      if ( $global_id != $term_id ) {
1940          if ( get_option( 'default_category' ) == $term_id ) {
1941              update_option( 'default_category', $global_id );
1942          }
1943  
1944          $wpdb->update( $wpdb->terms, array( 'term_id' => $global_id ), array( 'term_id' => $term_id ) );
1945          $wpdb->update( $wpdb->term_taxonomy, array( 'term_id' => $global_id ), array( 'term_id' => $term_id ) );
1946          $wpdb->update( $wpdb->term_taxonomy, array( 'parent' => $global_id ), array( 'parent' => $term_id ) );
1947  
1948          clean_term_cache( $term_id );
1949      }
1950      if ( $recurse_start ) {
1951          $global_terms_recurse = null;
1952      }
1953  
1954      return $global_id;
1955  }
1956  
1957  /**
1958   * Ensure that the current site's domain is listed in the allowed redirect host list.
1959   *
1960   * @see wp_validate_redirect()
1961   * @since MU (3.0.0)
1962   *
1963   * @param array|string $deprecated Not used.
1964   * @return array The current site's domain
1965   */
1966  function redirect_this_site( $deprecated = '' ) {
1967      return array( get_network()->domain );
1968  }
1969  
1970  /**
1971   * Check whether an upload is too big.
1972   *
1973   * @since MU (3.0.0)
1974   *
1975   * @blessed
1976   *
1977   * @param array $upload
1978   * @return string|array If the upload is under the size limit, $upload is returned. Otherwise returns an error message.
1979   */
1980  function upload_is_file_too_big( $upload ) {
1981      if ( ! is_array( $upload ) || defined( 'WP_IMPORTING' ) || get_site_option( 'upload_space_check_disabled' ) ) {
1982          return $upload;
1983      }
1984  
1985      if ( strlen( $upload['bits'] ) > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1986          /* translators: %s: maximum allowed file size in kilobytes */
1987          return sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ) );
1988      }
1989  
1990      return $upload;
1991  }
1992  
1993  /**
1994   * Add a nonce field to the signup page.
1995   *
1996   * @since MU (3.0.0)
1997   */
1998  function signup_nonce_fields() {
1999      $id = mt_rand();
2000      echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
2001      wp_nonce_field( 'signup_form_' . $id, '_signup_form', false );
2002  }
2003  
2004  /**
2005   * Process the signup nonce created in signup_nonce_fields().
2006   *
2007   * @since MU (3.0.0)
2008   *
2009   * @param array $result
2010   * @return array
2011   */
2012  function signup_nonce_check( $result ) {
2013      if ( ! strpos( $_SERVER['PHP_SELF'], 'wp-signup.php' ) ) {
2014          return $result;
2015      }
2016  
2017      if ( ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) {
2018          $result['errors']->add( 'invalid_nonce', __( 'Unable to submit this form, please try again.' ) );
2019      }
2020  
2021      return $result;
2022  }
2023  
2024  /**
2025   * Correct 404 redirects when NOBLOGREDIRECT is defined.
2026   *
2027   * @since MU (3.0.0)
2028   */
2029  function maybe_redirect_404() {
2030      if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) ) {
2031          /**
2032           * Filters the redirect URL for 404s on the main site.
2033           *
2034           * The filter is only evaluated if the NOBLOGREDIRECT constant is defined.
2035           *
2036           * @since 3.0.0
2037           *
2038           * @param string $no_blog_redirect The redirect URL defined in NOBLOGREDIRECT.
2039           */
2040          $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT );
2041          if ( $destination ) {
2042              if ( $destination == '%siteurl%' ) {
2043                  $destination = network_home_url();
2044              }
2045              wp_redirect( $destination );
2046              exit();
2047          }
2048      }
2049  }
2050  
2051  /**
2052   * Add a new user to a blog by visiting /newbloguser/{key}/.
2053   *
2054   * This will only work when the user's details are saved as an option
2055   * keyed as 'new_user_{key}', where '{key}' is a hash generated for the user to be
2056   * added, as when a user is invited through the regular WP Add User interface.
2057   *
2058   * @since MU (3.0.0)
2059   */
2060  function maybe_add_existing_user_to_blog() {
2061      if ( false === strpos( $_SERVER['REQUEST_URI'], '/newbloguser/' ) ) {
2062          return;
2063      }
2064  
2065      $parts = explode( '/', $_SERVER['REQUEST_URI'] );
2066      $key   = array_pop( $parts );
2067  
2068      if ( $key == '' ) {
2069          $key = array_pop( $parts );
2070      }
2071  
2072      $details = get_option( 'new_user_' . $key );
2073      if ( ! empty( $details ) ) {
2074          delete_option( 'new_user_' . $key );
2075      }
2076  
2077      if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) ) {
2078          wp_die( sprintf( __( 'An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.' ), home_url() ) );
2079      }
2080  
2081      wp_die( sprintf( __( 'You have been added to this site. Please visit the <a href="%1$s">homepage</a> or <a href="%2$s">log in</a> using your username and password.' ), home_url(), admin_url() ), __( 'WordPress &rsaquo; Success' ), array( 'response' => 200 ) );
2082  }
2083  
2084  /**
2085   * Add a user to a blog based on details from maybe_add_existing_user_to_blog().
2086   *
2087   * @since MU (3.0.0)
2088   *
2089   * @param array $details
2090   * @return true|WP_Error|void
2091   */
2092  function add_existing_user_to_blog( $details = false ) {
2093      if ( is_array( $details ) ) {
2094          $blog_id = get_current_blog_id();
2095          $result  = add_user_to_blog( $blog_id, $details['user_id'], $details['role'] );
2096  
2097          /**
2098           * Fires immediately after an existing user is added to a site.
2099           *
2100           * @since MU (3.0.0)
2101           *
2102           * @param int   $user_id User ID.
2103           * @param mixed $result  True on success or a WP_Error object if the user doesn't exist
2104           *                       or could not be added.
2105           */
2106          do_action( 'added_existing_user', $details['user_id'], $result );
2107  
2108          return $result;
2109      }
2110  }
2111  
2112  /**
2113   * Adds a newly created user to the appropriate blog
2114   *
2115   * To add a user in general, use add_user_to_blog(). This function
2116   * is specifically hooked into the {@see 'wpmu_activate_user'} action.
2117   *
2118   * @since MU (3.0.0)
2119   * @see add_user_to_blog()
2120   *
2121   * @param int   $user_id
2122   * @param mixed $password Ignored.
2123   * @param array $meta
2124   */
2125  function add_new_user_to_blog( $user_id, $password, $meta ) {
2126      if ( ! empty( $meta['add_to_blog'] ) ) {
2127          $blog_id = $meta['add_to_blog'];
2128          $role    = $meta['new_role'];
2129          remove_user_from_blog( $user_id, get_network()->site_id ); // remove user from main blog.
2130  
2131          $result = add_user_to_blog( $blog_id, $user_id, $role );
2132  
2133          if ( ! is_wp_error( $result ) ) {
2134              update_user_meta( $user_id, 'primary_blog', $blog_id );
2135          }
2136      }
2137  }
2138  
2139  /**
2140   * Correct From host on outgoing mail to match the site domain
2141   *
2142   * @since MU (3.0.0)
2143   *
2144   * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference).
2145   */
2146  function fix_phpmailer_messageid( $phpmailer ) {
2147      $phpmailer->Hostname = get_network()->domain;
2148  }
2149  
2150  /**
2151   * Check to see whether a user is marked as a spammer, based on user login.
2152   *
2153   * @since MU (3.0.0)
2154   *
2155   * @param string|WP_User $user Optional. Defaults to current user. WP_User object,
2156   *                             or user login name as a string.
2157   * @return bool
2158   */
2159  function is_user_spammy( $user = null ) {
2160      if ( ! ( $user instanceof WP_User ) ) {
2161          if ( $user ) {
2162              $user = get_user_by( 'login', $user );
2163          } else {
2164              $user = wp_get_current_user();
2165          }
2166      }
2167  
2168      return $user && isset( $user->spam ) && 1 == $user->spam;
2169  }
2170  
2171  /**
2172   * Update this blog's 'public' setting in the global blogs table.
2173   *
2174   * Public blogs have a setting of 1, private blogs are 0.
2175   *
2176   * @since MU (3.0.0)
2177   *
2178   * @param int $old_value
2179   * @param int $value     The new public value
2180   */
2181  function update_blog_public( $old_value, $value ) {
2182      update_blog_status( get_current_blog_id(), 'public', (int) $value );
2183  }
2184  
2185  /**
2186   * Check whether users can self-register, based on Network settings.
2187   *
2188   * @since MU (3.0.0)
2189   *
2190   * @return bool
2191   */
2192  function users_can_register_signup_filter() {
2193      $registration = get_site_option( 'registration' );
2194      return ( $registration == 'all' || $registration == 'user' );
2195  }
2196  
2197  /**
2198   * Ensure that the welcome message is not empty. Currently unused.
2199   *
2200   * @since MU (3.0.0)
2201   *
2202   * @param string $text
2203   * @return string
2204   */
2205  function welcome_user_msg_filter( $text ) {
2206      if ( ! $text ) {
2207          remove_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
2208  
2209          /* translators: Do not translate USERNAME, PASSWORD, LOGINLINK, SITE_NAME: those are placeholders. */
2210          $text = __(
2211              'Howdy USERNAME,
2212  
2213  Your new account is set up.
2214  
2215  You can log in with the following information:
2216  Username: USERNAME
2217  Password: PASSWORD
2218  LOGINLINK
2219  
2220  Thanks!
2221  
2222  --The Team @ SITE_NAME'
2223          );
2224          update_site_option( 'welcome_user_email', $text );
2225      }
2226      return $text;
2227  }
2228  
2229  /**
2230   * Whether to force SSL on content.
2231   *
2232   * @since 2.8.5
2233   *
2234   * @staticvar bool $forced_content
2235   *
2236   * @param bool $force
2237   * @return bool True if forced, false if not forced.
2238   */
2239  function force_ssl_content( $force = '' ) {
2240      static $forced_content = false;
2241  
2242      if ( '' != $force ) {
2243          $old_forced     = $forced_content;
2244          $forced_content = $force;
2245          return $old_forced;
2246      }
2247  
2248      return $forced_content;
2249  }
2250  
2251  /**
2252   * Formats a URL to use https.
2253   *
2254   * Useful as a filter.
2255   *
2256   * @since 2.8.5
2257   *
2258   * @param string $url URL
2259   * @return string URL with https as the scheme
2260   */
2261  function filter_SSL( $url ) {  // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
2262      if ( ! is_string( $url ) ) {
2263          return get_bloginfo( 'url' ); // Return home blog url with proper scheme
2264      }
2265  
2266      if ( force_ssl_content() && is_ssl() ) {
2267          $url = set_url_scheme( $url, 'https' );
2268      }
2269  
2270      return $url;
2271  }
2272  
2273  /**
2274   * Schedule update of the network-wide counts for the current network.
2275   *
2276   * @since 3.1.0
2277   */
2278  function wp_schedule_update_network_counts() {
2279      if ( ! is_main_site() ) {
2280          return;
2281      }
2282  
2283      if ( ! wp_next_scheduled( 'update_network_counts' ) && ! wp_installing() ) {
2284          wp_schedule_event( time(), 'twicedaily', 'update_network_counts' );
2285      }
2286  }
2287  
2288  /**
2289   * Update the network-wide counts for the current network.
2290   *
2291   * @since 3.1.0
2292   * @since 4.8.0 The `$network_id` parameter has been added.
2293   *
2294   * @param int|null $network_id ID of the network. Default is the current network.
2295   */
2296  function wp_update_network_counts( $network_id = null ) {
2297      wp_update_network_user_counts( $network_id );
2298      wp_update_network_site_counts( $network_id );
2299  }
2300  
2301  /**
2302   * Update the count of sites for the current network.
2303   *
2304   * If enabled through the {@see 'enable_live_network_counts'} filter, update the sites count
2305   * on a network when a site is created or its status is updated.
2306   *
2307   * @since 3.7.0
2308   * @since 4.8.0 The `$network_id` parameter has been added.
2309   *
2310   * @param int|null $network_id ID of the network. Default is the current network.
2311   */
2312  function wp_maybe_update_network_site_counts( $network_id = null ) {
2313      $is_small_network = ! wp_is_large_network( 'sites', $network_id );
2314  
2315      /**
2316       * Filters whether to update network site or user counts when a new site is created.
2317       *
2318       * @since 3.7.0
2319       *
2320       * @see wp_is_large_network()
2321       *
2322       * @param bool   $small_network Whether the network is considered small.
2323       * @param string $context       Context. Either 'users' or 'sites'.
2324       */
2325      if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'sites' ) ) {
2326          return;
2327      }
2328  
2329      wp_update_network_site_counts( $network_id );
2330  }
2331  
2332  /**
2333   * Update the network-wide users count.
2334   *
2335   * If enabled through the {@see 'enable_live_network_counts'} filter, update the users count
2336   * on a network when a user is created or its status is updated.
2337   *
2338   * @since 3.7.0
2339   * @since 4.8.0 The `$network_id` parameter has been added.
2340   *
2341   * @param int|null $network_id ID of the network. Default is the current network.
2342   */
2343  function wp_maybe_update_network_user_counts( $network_id = null ) {
2344      $is_small_network = ! wp_is_large_network( 'users', $network_id );
2345  
2346      /** This filter is documented in wp-includes/ms-functions.php */
2347      if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
2348          return;
2349      }
2350  
2351      wp_update_network_user_counts( $network_id );
2352  }
2353  
2354  /**
2355   * Update the network-wide site count.
2356   *
2357   * @since 3.7.0
2358   * @since 4.8.0 The `$network_id` parameter has been added.
2359   *
2360   * @param int|null $network_id ID of the network. Default is the current network.
2361   */
2362  function wp_update_network_site_counts( $network_id = null ) {
2363      $network_id = (int) $network_id;
2364      if ( ! $network_id ) {
2365          $network_id = get_current_network_id();
2366      }
2367  
2368      $count = get_sites(
2369          array(
2370              'network_id'             => $network_id,
2371              'spam'                   => 0,
2372              'deleted'                => 0,
2373              'archived'               => 0,
2374              'count'                  => true,
2375              'update_site_meta_cache' => false,
2376          )
2377      );
2378  
2379      update_network_option( $network_id, 'blog_count', $count );
2380  }
2381  
2382  /**
2383   * Update the network-wide user count.
2384   *
2385   * @since 3.7.0
2386   * @since 4.8.0 The `$network_id` parameter has been added.
2387   *
2388   * @global wpdb $wpdb WordPress database abstraction object.
2389   *
2390   * @param int|null $network_id ID of the network. Default is the current network.
2391   */
2392  function wp_update_network_user_counts( $network_id = null ) {
2393      global $wpdb;
2394  
2395      $count = $wpdb->get_var( "SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'" );
2396      update_network_option( $network_id, 'user_count', $count );
2397  }
2398  
2399  /**
2400   * Returns the space used by the current blog.
2401   *
2402   * @since 3.5.0
2403   *
2404   * @return int Used space in megabytes
2405   */
2406  function get_space_used() {
2407      /**
2408       * Filters the amount of storage space used by the current site.
2409       *
2410       * @since 3.5.0
2411       *
2412       * @param int|bool $space_used The amount of used space, in megabytes. Default false.
2413       */
2414      $space_used = apply_filters( 'pre_get_space_used', false );
2415      if ( false === $space_used ) {
2416          $upload_dir = wp_upload_dir();
2417          $space_used = get_dirsize( $upload_dir['basedir'] ) / MB_IN_BYTES;
2418      }
2419  
2420      return $space_used;
2421  }
2422  
2423  /**
2424   * Returns the upload quota for the current blog.
2425   *
2426   * @since MU (3.0.0)
2427   *
2428   * @return int Quota in megabytes
2429   */
2430  function get_space_allowed() {
2431      $space_allowed = get_option( 'blog_upload_space' );
2432  
2433      if ( ! is_numeric( $space_allowed ) ) {
2434          $space_allowed = get_site_option( 'blog_upload_space' );
2435      }
2436  
2437      if ( ! is_numeric( $space_allowed ) ) {
2438          $space_allowed = 100;
2439      }
2440  
2441      /**
2442       * Filters the upload quota for the current site.
2443       *
2444       * @since 3.7.0
2445       *
2446       * @param int $space_allowed Upload quota in megabytes for the current blog.
2447       */
2448      return apply_filters( 'get_space_allowed', $space_allowed );
2449  }
2450  
2451  /**
2452   * Determines if there is any upload space left in the current blog's quota.
2453   *
2454   * @since 3.0.0
2455   *
2456   * @return int of upload space available in bytes
2457   */
2458  function get_upload_space_available() {
2459      $allowed = get_space_allowed();
2460      if ( $allowed < 0 ) {
2461          $allowed = 0;
2462      }
2463      $space_allowed = $allowed * MB_IN_BYTES;
2464      if ( get_site_option( 'upload_space_check_disabled' ) ) {
2465          return $space_allowed;
2466      }
2467  
2468      $space_used = get_space_used() * MB_IN_BYTES;
2469  
2470      if ( ( $space_allowed - $space_used ) <= 0 ) {
2471          return 0;
2472      }
2473  
2474      return $space_allowed - $space_used;
2475  }
2476  
2477  /**
2478   * Determines if there is any upload space left in the current blog's quota.
2479   *
2480   * @since 3.0.0
2481   * @return bool True if space is available, false otherwise.
2482   */
2483  function is_upload_space_available() {
2484      if ( get_site_option( 'upload_space_check_disabled' ) ) {
2485          return true;
2486      }
2487  
2488      return (bool) get_upload_space_available();
2489  }
2490  
2491  /**
2492   * Filters the maximum upload file size allowed, in bytes.
2493   *
2494   * @since 3.0.0
2495   *
2496   * @param  int $size Upload size limit in bytes.
2497   * @return int       Upload size limit in bytes.
2498   */
2499  function upload_size_limit_filter( $size ) {
2500      $fileupload_maxk = KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 );
2501      if ( get_site_option( 'upload_space_check_disabled' ) ) {
2502          return min( $size, $fileupload_maxk );
2503      }
2504  
2505      return min( $size, $fileupload_maxk, get_upload_space_available() );
2506  }
2507  
2508  /**
2509   * Whether or not we have a large network.
2510   *
2511   * The default criteria for a large network is either more than 10,000 users or more than 10,000 sites.
2512   * Plugins can alter this criteria using the {@see 'wp_is_large_network'} filter.
2513   *
2514   * @since 3.3.0
2515   * @since 4.8.0 The `$network_id` parameter has been added.
2516   *
2517   * @param string   $using      'sites or 'users'. Default is 'sites'.
2518   * @param int|null $network_id ID of the network. Default is the current network.
2519   * @return bool True if the network meets the criteria for large. False otherwise.
2520   */
2521  function wp_is_large_network( $using = 'sites', $network_id = null ) {
2522      $network_id = (int) $network_id;
2523      if ( ! $network_id ) {
2524          $network_id = get_current_network_id();
2525      }
2526  
2527      if ( 'users' == $using ) {
2528          $count = get_user_count( $network_id );
2529          /**
2530           * Filters whether the network is considered large.
2531           *
2532           * @since 3.3.0
2533           * @since 4.8.0 The `$network_id` parameter has been added.
2534           *
2535           * @param bool   $is_large_network Whether the network has more than 10000 users or sites.
2536           * @param string $component        The component to count. Accepts 'users', or 'sites'.
2537           * @param int    $count            The count of items for the component.
2538           * @param int    $network_id       The ID of the network being checked.
2539           */
2540          return apply_filters( 'wp_is_large_network', $count > 10000, 'users', $count, $network_id );
2541      }
2542  
2543      $count = get_blog_count( $network_id );
2544      /** This filter is documented in wp-includes/ms-functions.php */
2545      return apply_filters( 'wp_is_large_network', $count > 10000, 'sites', $count, $network_id );
2546  }
2547  
2548  /**
2549   * Retrieves a list of reserved site on a sub-directory Multisite installation.
2550   *
2551   * @since 4.4.0
2552   *
2553   * @return array $names Array of reserved subdirectory names.
2554   */
2555  function get_subdirectory_reserved_names() {
2556      $names = array(
2557          'page',
2558          'comments',
2559          'blog',
2560          'files',
2561          'feed',
2562          'wp-admin',
2563          'wp-content',
2564          'wp-includes',
2565          'wp-json',
2566          'embed',
2567      );
2568  
2569      /**
2570       * Filters reserved site names on a sub-directory Multisite installation.
2571       *
2572       * @since 3.0.0
2573       * @since 4.4.0 'wp-admin', 'wp-content', 'wp-includes', 'wp-json', and 'embed' were added
2574       *              to the reserved names list.
2575       *
2576       * @param array $subdirectory_reserved_names Array of reserved names.
2577       */
2578      return apply_filters( 'subdirectory_reserved_names', $names );
2579  }
2580  
2581  /**
2582   * Send a confirmation request email when a change of network admin email address is attempted.
2583   *
2584   * The new network admin address will not become active until confirmed.
2585   *
2586   * @since 4.9.0
2587   *
2588   * @param string $old_value The old network admin email address.
2589   * @param string $value     The proposed new network admin email address.
2590   */
2591  function update_network_option_new_admin_email( $old_value, $value ) {
2592      if ( $value == get_site_option( 'admin_email' ) || ! is_email( $value ) ) {
2593          return;
2594      }
2595  
2596      $hash            = md5( $value . time() . mt_rand() );
2597      $new_admin_email = array(
2598          'hash'     => $hash,
2599          'newemail' => $value,
2600      );
2601      update_site_option( 'network_admin_hash', $new_admin_email );
2602  
2603      $switched_locale = switch_to_locale( get_user_locale() );
2604  
2605      /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2606      $email_text = __(
2607          'Howdy ###USERNAME###,
2608  
2609  You recently requested to have the network admin email address on
2610  your network changed.
2611  
2612  If this is correct, please click on the following link to change it:
2613  ###ADMIN_URL###
2614  
2615  You can safely ignore and delete this email if you do not want to
2616  take this action.
2617  
2618  This email has been sent to ###EMAIL###
2619  
2620  Regards,
2621  All at ###SITENAME###
2622  ###SITEURL###'
2623      );
2624  
2625      /**
2626       * Filters the text of the email sent when a change of network admin email address is attempted.
2627       *
2628       * The following strings have a special meaning and will get replaced dynamically:
2629       * ###USERNAME###  The current user's username.
2630       * ###ADMIN_URL### The link to click on to confirm the email change.
2631       * ###EMAIL###     The proposed new network admin email address.
2632       * ###SITENAME###  The name of the network.
2633       * ###SITEURL###   The URL to the network.
2634       *
2635       * @since 4.9.0
2636       *
2637       * @param string $email_text      Text in the email.
2638       * @param array  $new_admin_email {
2639       *     Data relating to the new network admin email address.
2640       *
2641       *     @type string $hash     The secure hash used in the confirmation link URL.
2642       *     @type string $newemail The proposed new network admin email address.
2643       * }
2644       */
2645      $content = apply_filters( 'new_network_admin_email_content', $email_text, $new_admin_email );
2646  
2647      $current_user = wp_get_current_user();
2648      $content      = str_replace( '###USERNAME###', $current_user->user_login, $content );
2649      $content      = str_replace( '###ADMIN_URL###', esc_url( network_admin_url( 'settings.php?network_admin_hash=' . $hash ) ), $content );
2650      $content      = str_replace( '###EMAIL###', $value, $content );
2651      $content      = str_replace( '###SITENAME###', wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ), $content );
2652      $content      = str_replace( '###SITEURL###', network_home_url(), $content );
2653  
2654      /* translators: Email change notification email subject. %s: Network title */
2655      wp_mail( $value, sprintf( __( '[%s] Network Admin Email Change Request' ), wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ) ), $content );
2656  
2657      if ( $switched_locale ) {
2658          restore_previous_locale();
2659      }
2660  }
2661  
2662  /**
2663   * Send an email to the old network admin email address when the network admin email address changes.
2664   *
2665   * @since 4.9.0
2666   *
2667   * @param string $option_name The relevant database option name.
2668   * @param string $new_email   The new network admin email address.
2669   * @param string $old_email   The old network admin email address.
2670   * @param int    $network_id  ID of the network.
2671   */
2672  function wp_network_admin_email_change_notification( $option_name, $new_email, $old_email, $network_id ) {
2673      $send = true;
2674  
2675      // Don't send the notification to the default 'admin_email' value.
2676      if ( 'you@example.com' === $old_email ) {
2677          $send = false;
2678      }
2679  
2680      /**
2681       * Filters whether to send the network admin email change notification email.
2682       *
2683       * @since 4.9.0
2684       *
2685       * @param bool   $send       Whether to send the email notification.
2686       * @param string $old_email  The old network admin email address.
2687       * @param string $new_email  The new network admin email address.
2688       * @param int    $network_id ID of the network.
2689       */
2690      $send = apply_filters( 'send_network_admin_email_change_email', $send, $old_email, $new_email, $network_id );
2691  
2692      if ( ! $send ) {
2693          return;
2694      }
2695  
2696      /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
2697      $email_change_text = __(
2698          'Hi,
2699  
2700  This notice confirms that the network admin email address was changed on ###SITENAME###.
2701  
2702  The new network admin email address is ###NEW_EMAIL###.
2703  
2704  This email has been sent to ###OLD_EMAIL###
2705  
2706  Regards,
2707  All at ###SITENAME###
2708  ###SITEURL###'
2709      );
2710  
2711      $email_change_email = array(
2712          'to'      => $old_email,
2713          /* translators: Network admin email change notification email subject. %s: Network title */
2714          'subject' => __( '[%s] Network Admin Email Changed' ),
2715          'message' => $email_change_text,
2716          'headers' => '',
2717      );
2718      // get network name
2719      $network_name = wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES );
2720  
2721      /**
2722       * Filters the contents of the email notification sent when the network admin email address is changed.
2723       *
2724       * @since 4.9.0
2725       *
2726       * @param array $email_change_email {
2727       *            Used to build wp_mail().
2728       *
2729       *            @type string $to      The intended recipient.
2730       *            @type string $subject The subject of the email.
2731       *            @type string $message The content of the email.
2732       *                The following strings have a special meaning and will get replaced dynamically:
2733       *                - ###OLD_EMAIL### The old network admin email address.
2734       *                - ###NEW_EMAIL### The new network admin email address.
2735       *                - ###SITENAME###  The name of the network.
2736       *                - ###SITEURL###   The URL to the site.
2737       *            @type string $headers Headers.
2738       *        }
2739       * @param string $old_email  The old network admin email address.
2740       * @param string $new_email  The new network admin email address.
2741       * @param int    $network_id ID of the network.
2742       */
2743      $email_change_email = apply_filters( 'network_admin_email_change_email', $email_change_email, $old_email, $new_email, $network_id );
2744  
2745      $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
2746      $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
2747      $email_change_email['message'] = str_replace( '###SITENAME###', $network_name, $email_change_email['message'] );
2748      $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
2749  
2750      wp_mail(
2751          $email_change_email['to'],
2752          sprintf(
2753              $email_change_email['subject'],
2754              $network_name
2755          ),
2756          $email_change_email['message'],
2757          $email_change_email['headers']
2758      );
2759  }


Generated: Fri Aug 23 08:20:01 2019 Cross-referenced by PHPXref 0.7